//*- coding = utf-8 -*-
//@Time : 2022-11-16 11:30
//@Author : 沉默小管
//@File : jwtAuth.guard.js
//@web  : golangblog.blog.csdn.net
//@Software: WebStorm
import {
  ExecutionContext, HttpException, HttpStatus,
  Injectable,
  UnauthorizedException
} from "@nestjs/common";
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';

/**
 * @guard文件作用:守卫
 */
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  private curApp;
  //用户登陆路劲
  private loginUrl = "/user/login"
  // 白名单路径
  private whiteUrlList: string[] = [this.loginUrl];
  constructor(app:any) {
    super();
    this.curApp = app
  }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    console.log('进入全局守卫');
    const req = context.switchToHttp().getRequest();

    try {
      // 获取token
      const accessToken = req.get('X-CSRF-TOKEN');
      /**
       * 记录用户登陆
       */
      if(req.url!=this.loginUrl || accessToken){

        let authService = this.curApp.get(AuthService);
        // //无差别加入操作记录
        // handleRecordLogs(2,{detail:"请求url:"+req.url+" 请求ip:"+clientIp,status:"success"})
        let user = await authService.verifyToken(accessToken);
        if (Object.keys(user).length > 0) {
          let requestMethod = req.method
          if(requestMethod.toLowerCase()=="post"){
            req.body = {
              ...req.body,
              uid:user.id
            }
          }else{
            req.query = {
              ...req.query,
              uid:user.id
            }
            req.url = req.url+"&uid="+user.id;
          }
          return true;
        }else{
          return false;
        }
      }else if(this.hasUrl(this.whiteUrlList, req.url)){
        return true;
      }else{
        throw new UnauthorizedException('请先登录');
      }
      // if (!accessToken) throw new UnauthorizedException('请先登录');
    } catch (e) {
      throw new HttpException(e,HttpStatus.SERVICE_UNAVAILABLE)
    }
  }
  // 验证该次请求是否为白名单内的路由
  private hasUrl(urlList: string[], url: string): boolean {
    let flag = false;
    if (urlList.indexOf(url) !== -1) {
      flag = true;
    }
    return flag;
  }
}

